<?php

namespace App\Service\WorkOrder;

use App\Enums\BaseErrorCode;
use App\Enums\Workflow\WorkflowV2Enum;
use App\Enums\WorkOrder\ErrCode;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Jobs\Appraise\Appraise;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\Appraise\AppraiseModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\Workflow\WorkflowV2OrderLogModel;
use App\Models\Workflow\WorkflowV2OrderModel;
use App\Models\Workflow\WorkflowV2OrderNodeModel;
use App\Models\Workflow\WorkflowV2TemplateModel;
use App\Models\WorkOrder\WorkflowV2TypeModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerSubmitHistoryModel;
use App\Models\WorkOrder\WorkOrderGatherModel;
use App\Models\WorkOrder\WorkOrderMainV2Model;
use App\Models\WorkOrder\WorkOrderMissionModel;
use App\Models\WorkOrder\WorkOrderOperateLogModel;
use App\Models\WorkOrder\WorkOrderRejectDetailModel;
use App\Models\WorkOrder\WorkOrderRejectModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Feishu\FeishuImageRemote;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Rms\RmsCameraRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Cruise\Mission\WorkflowV2InputService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Workflow\WorkflowV2OrderService;
use App\Service\WorkOrder\Message\SendFsService;
use App\Service\WorkOrder\Mission\MissionEngineService;
use App\Service\WorkOrder\Mission\MissionNoticeService;
use App\Service\WorkOrder\Reject\WorkOrderRejectService;
use App\Support\CustomForm\AttributeWorkOrderSupport;
use App\Support\CustomForm\ValidateSupport;
use Carbon\Carbon;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;
use Kuafu\GeneralFs\BuildFs;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProblemFeedbackService
{

    public static function problemList()
    {
        $list = [];
        foreach (OrderEnum::PROBLEM_FEEDBACK_LIST ?? [] as $k => $item) {
            $list[] = [
                'value' => $k,
                'name'  => $item
            ];
        }
        return $list;
    }

    /**
     * @return array
     */
    public static function problemType(): array
    {
        // 问题反馈问题列表
        $problemType = collect(OrderEnum::PROBLEM_FEEDBACK_TYPE_LIST)->map(function ($type) {
            $type["child"] = enumToSelection($type["child"]);
            return $type;
        })->values()->toArray();

        $tempProblemType = array_column($problemType, null, 'key');

        // 添加审批流的工单 获得工单审批流
        $workOrderApprovalModel = WorkflowV2TemplateModel::query()
            ->where('workflowType', WorkflowV2Enum::WORKFLOW_TYPE_WORK_ORDER)
            ->where('status', WorkflowV2TemplateModel::STATUS_ON)
            ->select(['id', 'name', 'workflowType2'])
            ->get();

        $workflowV2TypeModels = WorkflowV2TypeModel::query()
            ->whereIn('id', $workOrderApprovalModel->pluck('workflowType2')->toArray())
            ->orWhereIn('id', [1, 2, 3, 4])
            ->orderBy('sort')
            ->get();

        $problemType = [];
        $workflowV2TypeModels->map(function (WorkflowV2TypeModel $workflowV2TypeModel) use ($tempProblemType, $workOrderApprovalModel, &$problemType) {
            if (isset($tempProblemType[$workflowV2TypeModel->name])) {
                $data = $tempProblemType[$workflowV2TypeModel->name];
            } else {
                $data = [
                    "value" => $workflowV2TypeModel->id,
                    "key"   => $workflowV2TypeModel->name,
                    "child" => [],
                    "desc"  => $workflowV2TypeModel->description
                ];
            }
            $data['icon'] = FileUtil::domain() . '/' . $workflowV2TypeModel->icon;

            $children = $workOrderApprovalModel
                ->where('workflowType2', $workflowV2TypeModel->id)
                ->map(function ($item) {
                    return [
                        "key"     => $item->name,
                        "version" => 2,
                        "value"   => $item->id
                    ];
                })->toArray();

            if (isset($data['child'])) {
                $data['child'] = array_merge($data['child'], $children);
            } else {
                $data['child'] = $children;
            }

            $problemType[] = $data;
        });


        return [
            "problemType"  => $problemType,
            "appraiseType" => collect(AppraiseModel::APP_APPRAISE_TYPE_LIST)->values()->toArray(),// 评价反馈列表
        ];
    }

    /**
     * 获取问题表单
     * @param int $problemType
     * @param $problemValue
     * @param int $shopId
     * @param array $parameter 获取表单与展示表单
     * @param int $origin 判断来源 2 Web
     * @param string $workOrderNo
     * @param string $userMobile
     * @param int $userId
     * @param int $isWeb
     * @return array
     * @throws GuzzleException
     */
    public static function getProblemForm(
        int $problemType,
        $problemValue,
        int $shopId,
        array $parameter = [],
        int $origin = OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP,
        string $workOrderNo = '',
        string $userMobile = '',
        int $userId = 0,
        int $isWeb = 0
    ) {
        $res        = [];
        $cameraType = 0;
        $popDetail  = null;
        if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_WEB) {
            $isWeb = 1;
        }
        switch ($problemType) {
            case OrderEnum::PROBLEM_PID_1:
                $problemList = OrderEnum::PROBLEM_PID_1_CHILDREN_MAPPING;
                //问题类型维持在第一个
                self::getProblemType($problemList, $problemValue, $origin, $workOrderNo);

                switch ($problemValue) {
                    case null :
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) {
                                return $attribute->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_1:
                        self::getFormByDelivery($shopId, $isWeb);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }

                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    $res = $parameter[$attribute->getInputName()] ?? null;
                                    if ($res === null && in_array($attribute->getInputName(),
                                            array_keys(OrderEnum::DEFAULT_FIELD_MAPPING))) {
                                        $res = OrderEnum::DEFAULT_FIELD_MAPPING[$attribute->getInputName()];
                                    }
                                    return $res;
                                })->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_2:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_3:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_4:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_5:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_15:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_16:
                        self::getFormByDestroy($shopId, $isWeb);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_6:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_7:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_10:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_11:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_12:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_13:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_14:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_17:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_18:
                        self::getFormByDriver($shopId, $problemValue, $isWeb);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_8:
                        self::getFormByChange($shopId);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_9:
                        self::getFormByStorageOther($shopId);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_19:
                    case OrderEnum::PROBLEM_PID_1_CHILDREN_20:
                        self::getFormByRection($shopId);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                }
                break;
            case OrderEnum::PROBLEM_PID_2:
                $problemList = OrderEnum::PROBLEM_PID_2_CHILDREN_MAPPING;
                //问题类型维持在第一个

                self::getProblemType($problemList, $problemValue, OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP,
                    $workOrderNo);
                switch ($problemValue) {
                    case null :
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) {
                                return $attribute->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_1:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_2:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_3:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_4:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_5:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_6:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_7:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_8:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_9:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_10:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_11:
                    case OrderEnum::PROBLEM_PID_2_CHILDREN_12:
                        self::getFormByQuality($shopId, $isWeb);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                }
                break;
            case OrderEnum::PROBLEM_PID_4:
                if (in_array($problemValue, array_keys(OrderEnum::PROBLEM_PID_4_CHILDREN_EQUIP_MAPPING))) {
                    $problemList = OrderEnum::PROBLEM_PID_4_CHILDREN_EQUIP_MAPPING;
                } else {
                    $problemList = OrderEnum::PROBLEM_PID_4_CHILDREN_SOFT_MAPPING;
                }

                if ($problemValue == OrderEnum::PROBLEM_PID_4_CHILDREN_11) {
                    $shopCamera = RmsCameraRemote::shopCamera($shopId)["list"];
                    if ($shopCamera) {
                        $lastCamera = end($shopCamera);
                        $cameraType = $lastCamera["type"];
                    }
                }

                if (in_array($problemValue, [
                    OrderEnum::PROBLEM_PID_4_CHILDREN_11,
                    OrderEnum::PROBLEM_PID_4_CHILDREN_12
                ])) {
                    $contactConfig = ConfigModel::query()
                                                ->where('module', 'workOrder')
                                                ->where('name', 'monitoringContact')
                                                ->value('value');
                    $data          = [];
                    if ($contactConfig) {
                        $popAll = json_decode($contactConfig, true);
                        switch ($problemValue) {
                            case OrderEnum::PROBLEM_PID_4_CHILDREN_12:
                                $popDetail = $popAll[$problemType][OrderEnum::PROBLEM_PID_4_CHILDREN_9] ?? [];
                                break;
                            case  OrderEnum::PROBLEM_PID_4_CHILDREN_11:
                                switch ($cameraType) {
                                    case 1:
                                        $popDetail = $popAll[$problemType][OrderEnum::PROBLEM_PID_4_CHILDREN_3] ?? [];
                                        break;
                                    case 2:
                                        $popDetail = $popAll[$problemType][OrderEnum::PROBLEM_PID_4_CHILDREN_4] ?? [];
                                        break;
                                }
                                break;
                        }
                    }
                }

                //问题类型维持在第一个
                self::getProblemType(
                    $problemList,
                    $problemValue,
                    OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP,
                    $workOrderNo,
                    $problemType,
                );
                switch ($problemValue) {
                    case null :
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) {
                                return $attribute->build();
                            })->values()->toArray();
                        break;
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_1:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_2:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_3:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_4:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_5:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_6:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_7:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_8:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_9:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_10:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_11:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_12:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_13:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_14:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_15:
                    case OrderEnum::PROBLEM_PID_4_CHILDREN_16:
                        self::getFormByEquipment($shopId, $userMobile);
                        $res = collect(AttributeWorkOrderSupport::$attributesMap)
                            ->map(function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                                if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                    return $attribute->build();
                                }
                                return $attribute->setValue(function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                })->build();
                            })->values()->toArray();
                        break;
                }
                break;
            case OrderEnum::PROBLEM_PID_6:
            case OrderEnum::PROBLEM_PID_7:
            case OrderEnum::PROBLEM_PID_8:
            case OrderEnum::PROBLEM_PID_9:
            case OrderEnum::PROBLEM_PID_10:
                self::getCustomerChannelForm($shopId, $userId);
                $res = collect(AttributeWorkOrderSupport::$attributesMap)
                    ->map(
                        function (AttributeWorkOrderSupport $attribute) use ($origin, $parameter) {
                            if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_APP) {
                                return $attribute->build();
                            }
                            return $attribute->setValue(
                                function () use ($parameter, $attribute) {
                                    if ($attribute->getInputName() == OrderEnum::FORM_BOOK_NO) {
                                        return ($parameter[$attribute->getInputName()] ?? [])[0] ?? null;
                                    } else {
                                        return $parameter[$attribute->getInputName()] ?? null;
                                    }
                                },
                            )->build();
                        },
                    )->values()->toArray();
                break;
        }

        $desc = OrderEnum::PROBLEM_FEEDBACK_DESC[$problemType] ?? '-';
        if ($problemType == OrderEnum::PROBLEM_PID_2) {// 品质问题子类 单独查
            $desc = OrderEnum::PROBLEM_PID_2_CHILDREN_DESC_MAPPING[$problemValue] ?? '-';
        } elseif ($problemType == OrderEnum::PROBLEM_PID_1) {// 仓储配送问题子类 单独查
            $desc = OrderEnum::PROBLEM_PID_1_CHILDREN_DESC_MAPPING[$problemValue] ?? '-';
        }
        return [
            'title'      => OrderEnum::PROBLEM_FEEDBACK_LIST[$problemType] ?? '-',
            'desc'       => $desc,
            'problemPid' => $problemType,
            'form'       => $res,
            "cameraType" => $cameraType,
            "popDetail"  => $popDetail
        ];
    }

    //问题类型
    public static function getProblemType($problemList, $problemValue, $origin, $workOrderNo, $problemType = 0)
    {
        AttributeWorkOrderSupport::setApplyMainModel($workOrderNo);
        AttributeWorkOrderSupport::getInstance('problemChildId', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '问题类型')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValue(function () use ($problemValue) {
                                     return $problemValue === null ? null : (int)$problemValue;
                                 })
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions($problemList)
                                 ]);
        if ($origin == OrderEnum::PROBLEM_FEEDBACK_INFO_USE_WEB) {
            AttributeWorkOrderSupport::$attributesMap->problemChildId->setCustomAttribute(['disabled', true]);
        }

        // 设备工单-故障详情（增加选项）
        if ($problemType == OrderEnum::PROBLEM_PID_4 && in_array($problemValue, array_keys(OrderEnum::PROBLEM_PID_4_CHILDREN_EQUIP_MAPPING))) {
            $config = ConfigModel::getSingleConfig(
                'workOrder',
                'childDescConfig',
                function ($data) {
                    return json_decode($data, true);
                },
                getSwitchCacheTime(3600),
            );
            $config = collect($config)->where('problemPid', $problemType)->first()['data'] ?? [];

            $childDescArr = $config[$problemValue] ?? [];
            if ($childDescArr) {
                AttributeWorkOrderSupport::getInstance('problemDescId', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '故障详情')
                    ->setCustomAttribute(['icon', 'arrow-right'])
                    ->setValidateRules(ValidateSupport::getInstance(true))
                    ->setCustomAttribute(
                        [
                            'options',
                            AttributeWorkOrderSupport::setSelectOptions($childDescArr)
                        ],
                    );
            }
        }
    }


    /*
     * 延迟配送/恢复配送表单
     */
    public static function getFormByDelivery(int $shopId, int $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE, '订货单号')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['isSearch', true])
                                 ->setCustomAttribute(['disabledToast', '暂无订单'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('delayDeliverType', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '您需要')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::PROBLEM_PID_1_CHILDREN_1_CHILDREN_MAPPING)
                                 ]);
        AttributeWorkOrderSupport::getInstance('delayDeliverClassify1', AttributeWorkOrderSupport::INPUT_TYPE_SELECT,
            '期望送达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::EXPECT_DATE_SOON_MAPPING)
                                 ])
                                 ->setRelations(['delayDeliverType', OrderEnum::PROBLEM_PID_1_CHILDREN_1_CHILDREN_1])
                                 ->setValue(function () {
                                     return OrderEnum::EXPECT_DATE_SOON;
                                 });
        AttributeWorkOrderSupport::getInstance('delayDeliverClassify2', AttributeWorkOrderSupport::INPUT_TYPE_SELECT,
            '期望送达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::EXPECT_DATE_SPECIFIC_MAPPING)
                                 ])
                                 ->setRelations(['delayDeliverType', OrderEnum::PROBLEM_PID_1_CHILDREN_1_CHILDREN_2])
                                 ->setValue(function () {
                                     return OrderEnum::EXPECT_DATE_SPECIFIC;
                                 });
        AttributeWorkOrderSupport::getInstance('delayDeliverDate1', AttributeWorkOrderSupport::INPUT_DATE, '选择日期')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD'])
                                 ->setRelations(['delayDeliverClassify2', OrderEnum::EXPECT_DATE_DELAY])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('delayDeliverDate2', AttributeWorkOrderSupport::INPUT_DATE, '选择日期')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD'])
                                 ->setRelations(['delayDeliverClassify1', OrderEnum::EXPECT_DATE_DELAY])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValue('')
                                 ->setReject()
                                 ->setValidateRules(ValidateSupport::getInstance(true));

    }

    /*
     * 内包装破损表单
     * 数量差异表单
     * 品相差异表单
     * 温度异常表单
     */
    public static function getFormByDestroy(int $shopId, int $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '订货单号')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['disabledToast', '暂无订单'])
                                 ->setCustomAttribute(['isSearch', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('bookTime', AttributeWorkOrderSupport::INPUT_DATE, '订货时间')
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD'])
                                 ->setCustomAttribute(['disabledToast', '请先选择订货单号'])
                                 ->setCustomAttribute(['disabled', true]);
        AttributeWorkOrderSupport::getInstance('deliverArrivalTime', AttributeWorkOrderSupport::INPUT_DATETIME,
            '物流送达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD HH:ii:ss'])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('driverPhone', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '司机联系电话');

        //TODO 获取订单产品

        AttributeWorkOrderSupport::getInstance('errJdeCodes', AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE,
            '选择问题产品')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['popupType', 'newPage'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', AttributeWorkOrderSupport::setSelectOptions([])]);
        AttributeWorkOrderSupport::getInstance('errNum', AttributeWorkOrderSupport::INPUT_TYPE_TEXT, '问题产品数量')
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setReject()
                                 ->setValue('');
        AttributeWorkOrderSupport::getInstance('arrivalNoteImg', AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX,
            '到货单照片')
                                 ->setCustomAttribute(['desc', '异常情况需要司机在订货单标注后，上传图片'])
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/0b/6a/005da9e86ee33da7d935111d3f6f0417010901cc67b11b4f1325188b5a51.jpg'
                                 ])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('productAbnormalImg',
            AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品异常处照片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
    }

    /*
     * 配送异常表单
     * 司机服务表单
     */
    public static function getFormByDriver(int $shopId, int $childType, int $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '订货单号')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['disabledToast', '暂无订单'])
                                 ->setCustomAttribute(['isSearch', true])
                                 ->setCustomAttribute(['popupType', 'slot'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('bookTime', AttributeWorkOrderSupport::INPUT_DATE, '订货时间')
                                 ->setCustomAttribute(['disabled', true])
                                 ->setCustomAttribute(['disabledToast', '请先选择订货单号'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD']);
        AttributeWorkOrderSupport::getInstance('deliverType', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '物流状态')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::DELIVER_STATUS_MAPPING)
                                 ]);
        AttributeWorkOrderSupport::getInstance('deliverArrivalTime', AttributeWorkOrderSupport::INPUT_DATETIME,
            '物流到达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD HH:ii:ss'])
                                 ->setRelations(['deliverType', OrderEnum::DELIVER_STATUS_1]);
        AttributeWorkOrderSupport::getInstance('driverPhone', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '司机联系电话');
        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValue('')
                                 ->setReject()
                                 ->setValidateRules(ValidateSupport::getInstance(true));

        if (OrderEnum::PROBLEM_PID_1_CHILDREN_6 == $childType) {
            AttributeWorkOrderSupport::getInstance('arrivalNoteImg',
                AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX,
                '到货单照片')
                                     ->setCustomAttribute(['desc', '异常情况需要司机在订货单标注后，上传图片'])
                                     ->setCustomAttribute(['download', true])
                                     ->setCustomAttribute([
                                         'descImg',
                                         'https://file.51kuafu.com/0b/6a/005da9e86ee33da7d935111d3f6f0417010901cc67b11b4f1325188b5a51.jpg'
                                     ])
                                     ->setCustomAttribute(['check', true])
                                     ->setValidateRules(ValidateSupport::getInstance(true));

            AttributeWorkOrderSupport::getInstance('productAbnormalImg',
                AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品异常处照片')
                                     ->setCustomAttribute(['download', true])
                                     ->setCustomAttribute(['check', true])
                                     ->setValidateRules(ValidateSupport::getInstance(true));
        }
    }

    /*
     * 统配信息变更表单
     */
    public static function getFormByChange(int $shopId)
    {

        $address = self::getDeliveryAddressByShopIdByShopId($shopId);
        AttributeWorkOrderSupport::getInstance('receiverName', AttributeWorkOrderSupport::INPUT_TYPE_TEXT, '配送人姓名')
                                 ->setValue($address['userName'] ?? null);
        AttributeWorkOrderSupport::getInstance('receiverPhone', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '配送人电话')
                                 ->setValue($address['phone'] ?? null);
        AttributeWorkOrderSupport::getInstance('receiverAddressPrefix',
            AttributeWorkOrderSupport::INPUT_TYPE_REGIONAL_LINKAGE,
            '统配配送区域')
                                 ->setValue($address['areaPrefix'] ?? []);
        AttributeWorkOrderSupport::getInstance('receiverAddress', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA,
            '详细地址')
                                 ->setValue($address['address'] ?? '');
    }

    /*
     * 品控问题表单
     */
    public static function getFormByQuality(int $shopId, $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '订货单号')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['disabledToast', '暂无订单'])
                                 ->setCustomAttribute(['isSearch', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('bookTime', AttributeWorkOrderSupport::INPUT_DATE, '订货时间')
                                 ->setCustomAttribute(['disabled', true])
                                 ->setCustomAttribute(['disabledToast', '请先选择订货单号'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD']);
        AttributeWorkOrderSupport::getInstance('deliverArrivalTime', AttributeWorkOrderSupport::INPUT_DATETIME,
            '物流到达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD HH:ii:ss'])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        //TODO 获取订单产品

        AttributeWorkOrderSupport::getInstance('errJdeCodes', AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE,
            '选择问题产品')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['popupType', 'newPage'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', AttributeWorkOrderSupport::setSelectOptions([])]);
        AttributeWorkOrderSupport::getInstance('errNum', AttributeWorkOrderSupport::INPUT_TYPE_NUMBER, '问题产品数量')
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('errProductUnit', AttributeWorkOrderSupport::INPUT_TYPE_TEXT, '问题产品单位')
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValue('')
                                 ->setReject()
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('arrivalNoteImg', AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX,
            '到货单照片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/29/ce/6a939478938d58a0190d9609b3fd11b003cbb543efcab2aab09ce808fe7f.png'
                                 ])
                                 ->setCustomAttribute([
                                     'desc',
                                     '为了更全面地了解货品信息为您解决问题，请您拍照时，到货单图片内信息：门店名称、到货日期、货品信息、签收人清晰可见'
                                 ])
                                 ->setValidateRules(ValidateSupport::getInstance(false));
        AttributeWorkOrderSupport::getInstance('productAbnormalImg',
            AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品异常处照片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/66/73/762399a759d22368c822564152e9654825e0d19b59c90a5829ec0c14603b.png'
                                 ])
                                 ->setCustomAttribute(['desc', '为了更全面地了解货品信息为您解决问题，请您拍照时，产品异常处图片内信息：产品异常或异物清晰可见'])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('productInnerLabelImg',
            AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品内袋标签图片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/05/0b/8498440f214e90d39be0f1810b934c9539114cb9f52f4b100fa3e6ac00b3.png'
                                 ])
                                 ->setCustomAttribute([
                                     'desc',
                                     '为了更全面地了解货品信息为您解决问题，请您拍照时，产品内袋标签图片内信息：货品名称、规格、生产厂家信息清晰可见'
                                 ])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('productCreatedDateImg',
            AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品内袋生产日期图片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/12/b3/ebdf9b681329785ca481502b42ed43ee669eedd855e3e3b11520af916673.png'
                                 ])
                                 ->setCustomAttribute(['desc', '为了更全面地了解货品信息为您解决问题，请您拍照时，产品内袋封口处信息：生产日期清晰可见'])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('manufactureTime', AttributeWorkOrderSupport::INPUT_DATE, '产品内袋生产日期')
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD']);
    }


    /*
     * 设备软装表单
     */
    public static function getFormByEquipment(int $shopId, string $userMobile = '')
    {
        //获得开业日期
        $mainProcessModel = OpenShopMainProcessModel::query()
                                                    ->with(['startBusinessRel'])
                                                    ->where('shopId', $shopId)->orderBy('id', 'desc')
                                                    ->first();

        if (null == $mainProcessModel) {
            $installTime = formatDateYmd(time());
        } else {
            if (null == $mainProcessModel->startBusinessRel) {
                $installTime = formatDateYmd(time());
            } else {
                $installTime = $mainProcessModel->startBusinessRel->startBusinessTime ? formatDateYmd($mainProcessModel->startBusinessRel->startBusinessTime) : formatDateYmd(time());
            }
        }


        AttributeWorkOrderSupport::getInstance('installTime', AttributeWorkOrderSupport::INPUT_DATE, '安装日期')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD'])
                                 ->setValue(function () use ($installTime) {
                                     return $installTime;
                                 });

        AttributeWorkOrderSupport::getInstance('isAffect', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '是否影响正常经营')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::EQUIPMENT_SOFT_MAPPING)
                                 ]);

        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValue('')
                                 ->setReject()
                                 ->setValidateRules(ValidateSupport::getInstance(true));

        AttributeWorkOrderSupport::getInstance('mobile', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '联系电话')
                                 ->setValue(function () use ($userMobile) {
                                     return $userMobile;
                                 })
                                 ->setValidateRules(ValidateSupport::getInstance(true));

        AttributeWorkOrderSupport::getInstance('equipmentImg', AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX,
            '设备故障图片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('equipmentVideo', AttributeWorkOrderSupport::INPUT_TYPE_VIDEO_CHECK_BOX,
            '设备故障视频')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
    }


    //获取订单号
    public static function getOrmOrderAndGoodsByShopId($shopId, int $isWeb = 0)
    {
        $days         = Cache::remember('tiger:workOrder:kfosOrderDays', 120, function () {
            $days = ConfigModel::query()
                               ->where('module', 'workOrder')
                               ->where('name', 'kfosOrderDays')
                               ->value('value');
            if (!is_numeric($days)) {
                $days = -30;
            }
            return $days;
        });
        if ($isWeb) {//后台查询时间加倍
            $days = $days * 2;
        }
        $ormOrderList = OrmNewOrderRemote::getNewOrderByShopId($shopId, $days);
        $code         = $ormOrderList['code'] ?? -1;
        if ($code != 0) {
            return [];
        }
        $data = [];
        foreach ($ormOrderList['data'] as $datum) {
            $data[] = [
                'value' => $datum['code'],
                'text'  => $datum['code'],
                'time'  => $datum['create_time'],
                'price' => $datum['total_amount'],
            ];
        }

        return $data;
    }

    public static function getOrmOrderGoods(string $ormOrder)
    {
        $ormOrderGoods = OrmNewOrderRemote::getNewOrderGoodsByOrmOrder($ormOrder);
        $code          = $ormOrderGoods['code'] ?? -1;
        if ($code != 0) {
            return [];
        }
        return $ormOrderGoods['data'] ?? [];
    }


    public static function getDeliveryAddressByShopIdByShopId(int $shopId)
    {
        $address = OrmNewOrderRemote::getDeliveryAddressByShopIdByShopId($shopId);
        $code    = $address['code'] ?? -1;
        if ($code != 0) {
            return [];
        }
        return $address['data'] ?? [];
    }


    public static function addWorkOrder(
        $params,
        $shopId,
        $userId,
        bool $isBackend = false
    ) {
        $queryWorkOrderNo = $workOrderNo = $params['workOrderNo'] ?? '';
        if ($queryWorkOrderNo) {
            $applyMain = WorkOrderApplyMainModel::query()->where('workOrderNo', $queryWorkOrderNo)->first();
            if (!$applyMain || $applyMain->status != OrderEnum::MAIN_STATUS_ING) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前订单状态不允许修改");
            }
        }

        //获取资源文件
        $fileArr          = [];
        $bookNo           = [];
        $extra            = [];
        $params['bookNo'] = (array)($params['bookNo'] ?? []);
        switch ($params['problemPid'] ?? 0) {
            case 0:
                break;

            case OrderEnum::PROBLEM_PID_1:
                $fileArr = OrderEnum::PROBLEM_PID_1_CHILDREN_FILE[$params['problemChildId']] ?? [];
                $bookNo  = $params['bookNo'];
                break;

            case OrderEnum::PROBLEM_PID_2:
                $fileArr = OrderEnum::PROBLEM_PID_2_CHILDREN_FILE[$params['problemChildId']] ?? [];
                $bookNo  = $params['bookNo'];
                break;

            case OrderEnum::PROBLEM_PID_4:
                $fileArr = OrderEnum::PROBLEM_PID_4_CHILDREN_FILE[$params['problemChildId']] ?? [];
                $bookNo  = $params['bookNo'];
                break;

            case OrderEnum::PROBLEM_PID_6:
            case OrderEnum::PROBLEM_PID_7:
            case OrderEnum::PROBLEM_PID_8:
            case OrderEnum::PROBLEM_PID_9:
            case OrderEnum::PROBLEM_PID_10:
                $fileArr = OrderEnum::PROBLEM_PID_6_10_CHILDREN_FILE ?? [];
                $params['solution'] = $params['problemSolution'];
                break;

        }
        if ($bookNo) {
            $extra = [
                'bookNo' => $bookNo,
            ];
        }

        //特殊处理  兼容前端
        if (isset($params[OrderEnum::FORM_ADDRESS_PREFIX])) {
            $area                                   = $params[OrderEnum::FORM_ADDRESS_PREFIX];
            $params[OrderEnum::FORM_ADDRESS_PREFIX] = [
                'provinceCode'  => $area[0]['value'] ?? 0,
                'cityCode'      => $area[1]['value'] ?? 0,
                'districtCode'  => $area[2]['value'] ?? 0,
                'addressPrefix' => ($area[0]['text'] ?? ($area[0] ?? '')) . '-' . ($area[1]['text'] ?? ($area[1] ?? '')) . '-' . ($area[2]['text'] ?? ($area[2] ?? '')),
            ];
        }

        $resources = [];
        foreach ($fileArr as $value) {
            if (!isset($params[$value])) {
                continue;
            }
            $resources[$value] = $params[$value];
            unset($params[$value]);
        }

        try {
            DB::beginTransaction();

            if ($queryWorkOrderNo) {

                // 更新
                WorkOrderApplyMainModel::query()->where('workOrderNo', $queryWorkOrderNo)
                                       ->update(['createdAt' => time(), 'createdByUid' => $userId]);

                WorkOrderApplyContentModel::query()->where('workOrderNo', $queryWorkOrderNo)->update([
                    'workOrderNo' => $queryWorkOrderNo,
                    'content'     => json_encode($params, JSON_UNESCAPED_UNICODE),
                ]);

                //通过订单号获取子业务ID
                $businessId = (int)WorkOrderApplyContentModel::query()
                                                             ->where('workOrderNo', $queryWorkOrderNo)
                                                             ->value('id');

                // 硬删之前的数据
                ResourcesModel::query()->where([
                    'businessId' => $businessId,
                    'module'     => ResourcesModel::MODULE_TYPE_WORK_ORDER,
                    'business'   => ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK
                ])->delete();

                $logContent = [
                    "parentType" => OrderEnum::PROBLEM_PID_TEXT[$applyMain->problemPid] ?? "",
                    "childType"  => OrderEnum::TYPE_RELATION_MAP[$applyMain->problemPid][$applyMain->problemChildId] ?? "",
                    "diff"       => []
                ];
                WorkOrderRejectModel::query()
                                    ->with("detailsRel")
                                    ->where("workOrderNo", $workOrderNo)
                                    ->where("status", WorkOrderRejectModel::STATUS_INIT)
                                    ->first()->detailsRel->each(function (
                        WorkOrderRejectDetailModel $orderRejectDetailModel
                    ) use ($params, $resources, &$logContent) {
                        $temp["field"]            = $orderRejectDetailModel->field;
                        $temp["fieldText"]        = $orderRejectDetailModel->fieldText;
                        $temp["fieldValue"]       = ["before" => $orderRejectDetailModel->fieldValue, "after" => null];
                        $temp["reasonOptionText"] = $orderRejectDetailModel->reasonOptionText;
                        $temp["isResource"]       = 0;
                        if (isset($params[$orderRejectDetailModel->field])) {
                            $temp["fieldValue"]["after"] = $params[$orderRejectDetailModel->field];
                        }
                        if (isset($resources[$orderRejectDetailModel->field])) {
                            $temp["isResource"]           = 1;
                            $temp["fieldValue"]["before"] = json_decode($temp["fieldValue"]["before"], true);
                            $temp["fieldValue"]["after"]  = collect($resources[$orderRejectDetailModel->field])
                                ->map(function (
                                    $resource
                                ) {
                                    return picturePath($resource);
                                })->values()->toArray();
                        }
                        array_push($logContent["diff"], $temp);
                    });


                // 驳回状态恢复
                $lastRejectUserId = (new WorkOrderRejectService('', $applyMain))->fixReject($userId);

                //日志 - 再次提交工单
                WorkOrderOperateLogModel::generateOperateLog(
                    $workOrderNo,
                    $applyMain->step,
                    WorkOrderOperateLogModel::TYPE_13,
                    request()->user()->username,
                    request()->user()->id,
                    json_encode($logContent, JSON_UNESCAPED_UNICODE),
                );

            } else {

                // 新增

                //基本添加 不包含文件资源
                $workOrderNo = WorkOrderBaseService::createWorkOrder($shopId, $params['problemPid'],
                    $params['problemChildId'], $params['problemDesc'] ?? '',
                    json_encode($params, JSON_UNESCAPED_UNICODE), $extra, $isBackend);

                //日志 - 提交工单
                WorkOrderOperateLogModel::generateOperateLog(
                    $workOrderNo,
                    MissionEnum::STEP_1,
                    WorkOrderOperateLogModel::TYPE_1,
                    request()->user()->username,
                    request()->user()->id,
                    vsprintf("%s - %s", [
                        OrderEnum::PROBLEM_PID_TEXT[$params["problemPid"]] ?? "",
                        OrderEnum::TYPE_RELATION_MAP[$params["problemPid"]][$params["problemChildId"]] ?? "",
                    ]),
                );
            }

            if (!empty($resources)) {
                //通过订单号获取子业务ID
                $businessId = (int)WorkOrderApplyContentModel::query()
                                                             ->where('workOrderNo', $workOrderNo)
                                                             ->value('id');
                $data       = [];
                //文件添加
                foreach ($resources as $key => $resource) {
                    if (is_array($resource)) {
                        foreach ($resource as $item) {
                            $data[] = [
                                'businessId'   => $businessId,
                                'module'       => ResourcesModel::MODULE_TYPE_WORK_ORDER,
                                'business'     => ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK,
                                'name'         => $key,
                                'url'          => getPrivateFileKey($item),
                                'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                                'createdAt'    => time(),
                                'updatedAt'    => time(),
                                'createdByUid' => $userId,
                                'updatedByUid' => $userId,
                            ];
                        }
                    }
                }

                ResourcesModel::query()->insert($data);
            }

            WorkOrderBaseService::syncWorkOrderGather($workOrderNo, $shopId);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('添加/编辑工单失败' . $e->getMessage());
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_ADD_WORK_ORDER_FAIL));
        }

        if ($queryWorkOrderNo) {

            // 驳回修改 - 通知处理人
            if ($lastRejectUserId) {
                (new SendFsService($queryWorkOrderNo))->kfDistributeProcessor(0, [$lastRejectUserId]);
            }
        } else {
            if ($isBackend) {
                self::backendWorkOrderInsertDetail($params, $workOrderNo);
            } else {
                // 正常提交 - 任务处理
                (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_1);

                // 仓储配送问题/品质异常问题 推送飞书群
                if ($params['problemPid'] == OrderEnum::PROBLEM_PID_1 || $params['problemPid'] == OrderEnum::PROBLEM_PID_2) {

                    dispatch(
                        (new Appraise(
                            [
                                'workOrderNo' => $workOrderNo,
                                'shopId'      => $shopId,
                                'createTime'  => time(),
                                'params'      => array_merge($params, $resources),
                            ],Appraise::TYPE_ADD_WORK_ORDER,
                        )),
                    )->onQueue(Appraise::QUEUE_NAME);

//                    self::sendFsMsg(
//                        [
//                            'workOrderNo' => $workOrderNo,
//                            'shopId'      => $shopId,
//                            'createTime'  => time(),
//                            'params'      => array_merge($params, $resources),
//                        ]
//                    );
                }
            }
        }

        return ["workOrderNo" => $workOrderNo];
    }

    /**
     * 添加问题工单
     * @param $templateId
     * @param $shopId
     * @param $userId
     * @return array
     */
    public static function getWorkOrderV2($templateId, $shopId, $userId): array
    {
        // 判断用户是否有未提交的工单
        $currentNodeIds = WorkflowV2OrderModel::query()
            ->where('shopId', $shopId)
            ->where('createdByUid', $userId)
            ->where('status', WorkflowV2OrderModel::STATUS_ING)
            ->pluck('currentNodeId')
            ->toArray();

        $workflowOrderIds = WorkflowV2OrderNodeModel::query()
            ->whereIn('id', $currentNodeIds)
            ->where('businessType', 1)
            ->pluck('workflowOrderId')
            ->toArray();

        if (count($workflowOrderIds)) {
            $cruiseOrderId = (int)WorkflowV2OrderModel::query()->where('id', $workflowOrderIds[0])->value('submitCruiseOrderId');
            return array_merge((new WorkflowV2InputService($cruiseOrderId, $userId))->getInputObjectFill(), ['workflowOrderId' => $workflowOrderIds[0]]);
        }

        // 通过审批流获得类型
        $workflowV2Template = WorkflowV2TemplateModel::query()->where('id', $templateId)->select(['id', 'workflowType', 'workflowType2'])->first();

        // 表单初始化
        $initFormData = (new WorkflowV2OrderService(0, $userId))->init($workflowV2Template->workflowType, $workflowV2Template->workflowType2, $shopId, 0);

        // 添加日志

        // 返回详情
        // 查询表单信息
        return array_merge((new WorkflowV2InputService($initFormData->submitCruiseOrderId, $userId))->getInputObjectFill(), ['workflowOrderId' => $initFormData->id]);
    }

    /**
     * @param array $params
     * @param string $workOrderNo
     */
    public static function backendWorkOrderInsertDetail(array $params, string $workOrderNo)
    {
        if ($params["isCompleted"]) {
            $customerId = WorkOrderApplyManagerModel::query()->insertGetId([
                'workOrderNo' => $workOrderNo,
                'role'        => WorkOrderUserRoleModel::ROLE_TYPE_1,
                'managerId'   => request()->user()->id,
                'managerName' => request()->user()->username,
                "remark"      => "系统自动确认",
                "solution"    => "",
                "submitTime"  => time()
            ]);

            $solutionId = WorkOrderApplyManagerModel::query()->insertGetId([
                'workOrderNo' => $workOrderNo,
                'role'        => OrderEnum::PROBLEM_PID_TO_ROLE[$params['problemPid']],
                'managerId'   => request()->user()->id,
                'managerName' => request()->user()->username,
                "remark"      => "系统自动确认",
                "solution"    => $params['solution'],
                "submitTime"  => time()
            ]);

            WorkOrderMissionModel::query()->insert([
                [
                    'workOrderNo'   => $workOrderNo,
                    'step'          => MissionEnum::STEP_2,
                    'dealUid'       => request()->user()->id,
                    'missionStatus' => MissionEnum::MISSION_STATUS_1,
                    'completeTime'  => time(),
                ],
                [
                    'workOrderNo'   => $workOrderNo,
                    'step'          => MissionEnum::STEP_4,
                    'dealUid'       => request()->user()->id,
                    'missionStatus' => MissionEnum::MISSION_STATUS_1,
                    'completeTime'  => time(),
                ]
            ]);

            //备注｜解决方案提交记录
            WorkOrderApplyManagerSubmitHistoryModel::query()->insert([
                [
                    "applyManagerId"  => $customerId,
                    "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_REMARK,
                    "content"         => "系统自动完成备注",
                    "createdByUid"    => request()->user()->id,
                    "createdUsername" => request()->user()->username,
                    "createdAt"       => time()
                ],
                [
                    "applyManagerId"  => $solutionId,
                    "type"            => WorkOrderApplyManagerSubmitHistoryModel::TYPE_SOLUTION,
                    "content"         => $params["solution"],
                    "createdByUid"    => request()->user()->id,
                    "createdUsername" => request()->user()->username,
                    "createdAt"       => time()
                ],
            ]);

            //日志 - 提交工单
            WorkOrderOperateLogModel::query()->insert(
                [
                    [
                        "workOrderNo"     => $workOrderNo,
                        "step"            => MissionEnum::STEP_2,
                        "type"            => WorkOrderOperateLogModel::TYPE_4,
                        "content"         => "系统自动提交备注",
                        "createdByUid"    => request()->user()->id,
                        "createdUsername" => request()->user()->username,
                        "createdAt"       => time()
                    ],
                    [
                        "workOrderNo"     => $workOrderNo,
                        "step"            => MissionEnum::STEP_4,
                        "type"            => WorkOrderOperateLogModel::TYPE_5,
                        "content"         => $params["solution"],
                        "createdByUid"    => request()->user()->id,
                        "createdUsername" => request()->user()->username,
                        "createdAt"       => time()
                    ],
                    [
                        "workOrderNo"     => $workOrderNo,
                        "step"            => MissionEnum::STEP_99,
                        "type"            => WorkOrderOperateLogModel::TYPE_14,
                        "content"         => "系统确认工单完成",
                        "createdByUid"    => request()->user()->id,
                        "createdUsername" => request()->user()->username,
                        "createdAt"       => time()
                    ]
                ],
            );

            WorkOrderApplyMainModel::saveStep($workOrderNo, MissionEnum::STEP_99);
            WorkOrderApplyMainModel::query()->where("workOrderNo", $workOrderNo)->update([
                "merchantConfirmFinishType"   => WorkOrderApplyMainModel::MERCHANT_CONFIRM_FINISH_TYPE_SYSTEM,
                "merchantConfirmFinishTime"   => time(),
                "merchantConfirmFinishStatus" => WorkOrderApplyMainModel::MERCHANT_CONFIRM_FINISH_STATUS_FINISH,
                "completeTime"                => strtotime($params["completeTime"])
            ]);
        } else {
            WorkOrderApplyManagerModel::query()->insert([
                'workOrderNo' => $workOrderNo,
                'role'        => WorkOrderUserRoleModel::ROLE_TYPE_1,
                'managerId'   => request()->user()->id,
                'managerName' => request()->user()->username,
                "remark"      => "系统自动确认",
                "submitTime"  => time(),
                "status"      => in_array($params['problemPid'], OrderEnum::NEW_GRAB_PIDS) ? WorkOrderApplyManagerModel::STATUS_OFF : WorkOrderApplyManagerModel::STATUS_ON,
            ]);
            WorkOrderMissionModel::query()->insert([
                'workOrderNo'   => $workOrderNo,
                'step'          => MissionEnum::STEP_2,
                'dealUid'       => request()->user()->id,
                'missionStatus' => MissionEnum::MISSION_STATUS_1,
                'completeTime'  => time(),
            ]);

            WorkOrderApplyMainModel::saveStep($workOrderNo, MissionEnum::STEP_2);
            //添加审批人记录
            $handle = $params['handle'] ?? [];
            if ($handle) {
                $handleArr   = [];
                $userNameArr = WorkOrderUserRoleModel::query()->whereIn('userId', $handle)->pluck('name', 'userId')
                                                     ->toArray();

                //获得已经拥有的处理记录
                $userIds = WorkOrderApplyManagerModel::query()
                                                     ->where('workOrderNo', $workOrderNo)
                                                     ->where('role', '>', WorkOrderUserRoleModel::ROLE_TYPE_1)
                                                     ->where('status', WorkOrderApplyManagerModel::STATUS_ON)
                                                     ->pluck('managerId')
                                                     ->toArray();

                foreach ($handle as $item) {
                    if (in_array($item, $userIds)) {
                        continue;
                    }
                    $handleArr[] = [
                        'workOrderNo'  => $workOrderNo,
                        'role'         => OrderEnum::PROBLEM_PID_TO_ROLE[$params['problemPid']] ?? 0,
                        'managerId'    => $item,
                        'managerName'  => $userNameArr[$item] ?? '',
                        'remark'       => '',
                        'solution'     => '',
                        'createdByUid' => request()->user()->id,
                        'updatedByUid' => request()->user()->id,
                        'createdAt'    => time(),
                        'updatedAt'    => time(),
                    ];
                }
                //添加审批记录
                WorkOrderApplyManagerModel::query()->insert($handleArr);
            }
            (new MissionEngineService($workOrderNo))->finish(MissionEnum::STEP_2);
        }
    }

    public static function feedbackProgressLists(int $shopId, int $pageNum, int $pageSize)
    {
        $workOrderGatherModel = WorkOrderGatherModel::query()
            ->where('shopId', $shopId)
            ->orderByDesc('createdAt')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $workOrder = $workOrderGatherModel->pluck('workOrderNo')->toArray();


        // $workOrderApplyMainModel = WorkOrderApplyMainModel::query()
        //                                     ->where('shopId', $shopId)
        //                                     ->where('step', '>', MissionEnum::STEP_1)
        //                                     ->where("sourceType", WorkOrderApplyMainModel::SOURCE_TYPE_0)
        //                                     ->orderByDesc('id')
        //                                     ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $list = [];
        WorkOrderApplyMainModel::query()
            ->whereIn('workOrderNo', $workOrder)
            ->get()
            ->map(function (WorkOrderApplyMainModel $workOrderApplyMainModel) use (&$list) {
                $list[] = [
                    'problemPidText' => $workOrderApplyMainModel->problemPidText,
                    'workOrderNo'    => $workOrderApplyMainModel->workOrderNo,
                    'createdAt'      => $workOrderApplyMainModel->createdAt->format('Y-m-d H:i'),
                    'sort'           => $workOrderApplyMainModel->createdAt->timestamp,
                    'status'         => $workOrderApplyMainModel->status,
                    'statusText'     => $workOrderApplyMainModel->mainStatusText,
                ];
            });

        // 需要合并新的工单问题 然后按照创建时间降序
        WorkflowV2OrderModel::query()
            ->where('shopId', $shopId)
            ->where('workflowType', WorkflowV2Enum::WORKFLOW_TYPE_WORK_ORDER)
            ->orderByDesc('id')
            ->get()
            ->map(function (WorkflowV2OrderModel $workflowV2OrderModel) use (&$list) {
                $list[] = [
                     'problemPidText' => $workflowV2OrderModel->name,
                     'workOrderNo'    => $workflowV2OrderModel->workflowNo,
                     'createdAt'      => $workflowV2OrderModel->createdAt->format('Y-m-d H:i'),
                     'sort'           => $workflowV2OrderModel->createdAt->timestamp,
                     'status'         => $workflowV2OrderModel->status,
                     'statusText'     => $workflowV2OrderModel->statusText,
                     'version'        => 2,
                 ];
            });

        return [
            'lists'    => collect($list)->sortByDesc('sort')->values()->toArray(),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'count'    => $workOrderGatherModel->total(),
        ];
    }

    public static function feedbackProgressDetail(string $workOrderNo)
    {
        $order = WorkOrderApplyMainModel::query()->where('workOrderNo', $workOrderNo)->first();
        if (!$order) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
        }

        // 开店订单督导
        $phone         = '';
        $mainProcessId = OpenShopMainProcessModel::query()->where('shopId', $order->shopId)->orderBy('id', 'desc')
                                                 ->value('id');
        if ($mainProcessId) {
            $uid = OpenShopOrderManagerModel::query()
                                            ->where('mainProcessId', $mainProcessId)
                                            ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                                            ->value('managerUid');
            if ($uid) {
                $user  = RmsUserService::getRmsUserInfoByUserIds([$uid], [], true);
                $phone = $user['data'][0]['mobile'] ?? '';
            }
        }

        $applyManagerModel = WorkOrderApplyManagerModel::query()
                                                       ->where('workOrderNo', $workOrderNo)
                                                       ->where("role", WorkOrderUserRoleModel::ROLE_TYPE_1)
                                                       ->where("status", WorkOrderApplyManagerModel::STATUS_ON)
                                                       ->first();
        $appraiseModel     = AppraiseModel::getInfoByWorkOrderNo($workOrderNo);//评价反馈详情
        return [
            'problemPidText'              => $order->problemPidText,
            'workOrderNo'                 => $order->workOrderNo,
            'problemChildIdText'          => $order->problemChildIdText,
            'problemPid'                  => $order->problemPid,
            'problemChildId'              => $order->problemChildId,
            'problemDesc'                 => $order->problemDesc,
            'merchantConfirmFinishStatus' => $order->merchantConfirmFinishStatus,
            'bookNo'                      => $order->extraArr['bookNo'] ?? [],
            'solutions'                   => $order->managerRel->pluck('solution')->filter()->values(),
            'status'                      => $order->status,
            'statusText'                  => $order->mainStatusText,
            'showUrged'                   => (int)MissionNoticeService::canPressNoticed($order), // 是否展示一件催办
            'supervisorPhone'             => $order->status == OrderEnum::MAIN_STATUS_FINISH ? "" : $phone, // 督导电话
            'customerRemark'              => $applyManagerModel ? $applyManagerModel->remark : "",
            'appraiseId'                  => $appraiseModel ? $appraiseModel->id : 0,
            'completeTime'                => formatDate($order->completeTime),
        ];
    }

    /**
     * 获得工单详情V2
     * @param string $workOrderNo
     * @return array
     */
    public static function feedbackProgressDetailV2(string $workOrderNo): array
    {
        $workOrder = WorkflowV2OrderModel::query()->where('workflowNo', $workOrderNo)->first();

        if (!$workOrder) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
        }

        $reSubmit = false;
        $workflowLogs = WorkflowV2OrderLogModel::query()
            ->where('workflowOrderId', $workOrder->id)
            ->whereIn('audit', [WorkflowV2OrderLogModel::AUDIT_YES, WorkflowV2OrderLogModel::AUDIT_NO])
            ->get()
            ->map(function (WorkflowV2OrderLogModel $workflowV2OrderLogModel) use (&$reSubmit) {
                $files    = $workflowV2OrderLogModel->imgFiles ? json_decode($workflowV2OrderLogModel->imgFiles, true) : [];
                $reSubmit = $workflowV2OrderLogModel->audit == WorkflowV2OrderLogModel::AUDIT_NO;
                return [
                    'handlerName' => $workflowV2OrderLogModel->handlerName,
                    'audit'       => $workflowV2OrderLogModel->audit,
                    'content'     => $workflowV2OrderLogModel->content,
                    'auditText'   => WorkflowV2OrderLogModel::AUDIT_TEXT[$workflowV2OrderLogModel->audit] ?? '-',
                    'createdAt'   => $workflowV2OrderLogModel->createdAt->format('Y-m-d H:i'),
                    'files'       => collect($files)->map(function ($file) {
                        $file['url'] = FileUtil::domain() . '/' . ltrim(parse_url($file['url'], PHP_URL_PATH), '/');
                        return $file;
                    })->toArray(),
                ];
            })->toArray();


        // 获得表单详情
        $formData = (new WorkflowV2InputService($workOrder->submitCruiseOrderId, $workOrder->createdByUid))->getInputObjectFill();

        return [
            'form'            => $formData,
            'progress'        => $workflowLogs,
            'reSubmit'        => $reSubmit,
            'name'            => $workOrder->name,
            'status'          => $workOrder->status,
            'statusText'      => WorkflowV2OrderModel::STATUS_TEXT[$workOrder->status] ?? '-',
            'workflowOrderId' => (int)WorkflowV2OrderModel::query()->where('prevOrderId', $workOrder->id)->where('workflowType', WorkflowV2Enum::WORKFLOW_TYPE_WORK_ORDER)->value('id')
        ];
    }

    private static function getFormByStorageOther(int $shopId, int $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '订货单号')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['isSearch', true])
                                 ->setCustomAttribute(['disabledToast', '暂无订单'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('bookTime', AttributeWorkOrderSupport::INPUT_DATE, '订货时间')
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD'])
                                 ->setCustomAttribute(['disabledToast', '请先选择订货单号'])
                                 ->setCustomAttribute(['disabled', true]);

        AttributeWorkOrderSupport::getInstance('deliverType', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '物流状态')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setCustomAttribute([
                                     'options',
                                     AttributeWorkOrderSupport::setSelectOptions(OrderEnum::DELIVER_STATUS_MAPPING)
                                 ]);

        AttributeWorkOrderSupport::getInstance('deliverArrivalTime', AttributeWorkOrderSupport::INPUT_DATETIME,
            '物流送达时间')
                                 ->setCustomAttribute(['icon', 'arrow-right'])
                                 ->setCustomAttribute(['format', 'YYYY-MM-DD HH:ii:ss'])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('driverPhone', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '司机联系电话');


        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
                                 ->setValidateRules(ValidateSupport::getInstance(true))
                                 ->setReject()
                                 ->setValue('');

        AttributeWorkOrderSupport::getInstance('arrivalNoteImg', AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX,
            '到货单照片')
                                 ->setCustomAttribute(['desc', '异常情况需要司机在订货单标注后，上传图片'])
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute([
                                     'descImg',
                                     'https://file.51kuafu.com/0b/6a/005da9e86ee33da7d935111d3f6f0417010901cc67b11b4f1325188b5a51.jpg'
                                 ])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
        AttributeWorkOrderSupport::getInstance('productAbnormalImg',
            AttributeWorkOrderSupport::INPUT_TYPE_ALBUM_CHECKBOX, '产品异常处照片')
                                 ->setCustomAttribute(['download', true])
                                 ->setCustomAttribute(['check', true])
                                 ->setValidateRules(ValidateSupport::getInstance(true));
    }


    /**
     * 获取全部供应商
     * @return array
     * @throws GuzzleException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function getOrmSupplierAll(): array
    {
        $ormOrderGoods = OrmNewOrderRemote::getOrmSupplier();
        $code          = $ormOrderGoods['code'] ?? -1;
        if ($code != 200) {
            return [];
        }
        return $ormOrderGoods['data']['list'] ?? [];
    }

    /**
     * 获取2和4供应商
     * @return array
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    public static function getOrmSupplier(): array
    {
        $factory          = [];
        $getOrmOrderGoods = self::getOrmSupplierAll();
        if ($getOrmOrderGoods) {
            collect($getOrmOrderGoods)->map(
                function ($item) use (&$factory) {
                    if (in_array($item['supplier_type'], [2, 4])) {
                        $name           = $item['company'] ? $item['company'] : $item['name'];
                        $factory[$item['id']] = [
                            'text'  => $name,
                            'value' => $item['id'],
                        ];
                    }
                },
            );
            if ($factory) {
                $factory = array_values($factory);
            }
        }
        return $factory;
    }


    /*
     * 新增400客服/企业微群渠道反馈的问题类型表单
     */
    public static function getCustomerChannelForm(int $shopId, int $userId)
    {
        $shopInfo   = (object)current((new RmsShopApi())->getShopByIds([$shopId])["data"]["shopList"]);//门店信息
        $userMobile = $shopInfo->shopMobile ?? "";

        AttributeWorkOrderSupport::getInstance('shopPhone', AttributeWorkOrderSupport::INPUT_TYPE_MOBILE, '门店联系方式')
            ->setValue($userMobile)
            ->setValidateRules(ValidateSupport::getInstance(true));//默认填充，门店RMS联系电话，可修改，微信

        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
            ->setValue('')
            ->setReject()
            ->setValidateRules(ValidateSupport::getInstance(true));

        AttributeWorkOrderSupport::getInstance(
            'problemImgVideo', AttributeWorkOrderSupport::INPUT_TYPE_FILE_CHECK_BOX,
            '反馈内容附件',
        )
            ->setCustomAttribute(['max', 9])
            ->setCustomAttribute(['download', true])
            ->setCustomAttribute(['check', true])
            ->setValidateRules(ValidateSupport::getInstance(false));

        AttributeWorkOrderSupport::getInstance('problemSolution', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '解决方案')
            ->setValue('')
            ->setReject()
            ->setValidateRules(ValidateSupport::getInstance(true));

        AttributeWorkOrderSupport::getInstance(
            'problemSolutionImgVideo', AttributeWorkOrderSupport::INPUT_TYPE_FILE_CHECK_BOX,
            '解决方案附件',
        )
            ->setCustomAttribute(['max', 9])
            ->setCustomAttribute(['download', true])
            ->setCustomAttribute(['check', true])
            ->setValidateRules(ValidateSupport::getInstance(false));

        $userList = WorkOrderUserRoleModel::query()
            ->groupBy('userId')
            ->selectRaw('userId as value,name as text')
            ->get()->toArray();

        AttributeWorkOrderSupport::getInstance('customerAccepted', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '客服受理人')
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setCustomAttribute(['disabledToast', ''])
            ->setCustomAttribute(['isSearch', true])
            ->setCustomAttribute(['popupType', 'slot'])
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setCustomAttribute(['options', $userList])
            ->setValue($userId);

        AttributeWorkOrderSupport::getInstance('problemAccepted', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '问题受理人')
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setCustomAttribute(['disabledToast', ''])
            ->setCustomAttribute(['isSearch', true])
            ->setCustomAttribute(['popupType', 'slot'])
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setCustomAttribute(['options', $userList])
            ->setValue($userId);
    }


    /*
     * 直配物流信息表单
     * 直配品质问题表单
     */
    public static function getFormByRection(int $shopId, int $isWeb = 0)
    {
        //TODO 获取订货订单号

        $ormOrderList = self::getOrmOrderAndGoodsByShopId($shopId, $isWeb);

        AttributeWorkOrderSupport::getInstance('bookNo', AttributeWorkOrderSupport::INPUT_TYPE_SELECT, '订货单号')
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setCustomAttribute(['disabledToast', '暂无订单'])
            ->setCustomAttribute(['isSearch', true])
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setCustomAttribute(['options', $ormOrderList]);

        if (empty($ormOrderList)) {
            AttributeWorkOrderSupport::$attributesMap->bookNo->setCustomAttribute(['disabled', true]);
        }

        AttributeWorkOrderSupport::getInstance('problemDesc', AttributeWorkOrderSupport::INPUT_TYPE_TEXTAREA, '问题描述')
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setReject()
            ->setValue('');
    }

    /**
     * 品质异常问题 推送飞书群
     * @param array $data
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    public static function sendFsMsg(array $data)
    {
        $workOrderNo = $data['workOrderNo'];
        $shopId      = $data['shopId'];
        $createTime  = $data['createTime'];
        $params      = $data['params'];

        $shopInfo = (object)current((new RmsShopApi())->getShopByIds([$shopId])['data']['shopList']);//门店信息
        $shopCode = $shopInfo->shopCode ?? '';
        $shopName = $shopCode . ($shopInfo->name ?? '');

        // 工单类型
        $problemPid         = $params['problemPid'];
        $problemChildId     = $params['problemChildId'];
        $problemPidText     = OrderEnum::PROBLEM_PID_TEXT[$problemPid] ?? '';

        if ($problemPid == OrderEnum::PROBLEM_PID_1) {// 仓储配送问题
            $problemChildIdText = OrderEnum::PROBLEM_PID_1_CHILDREN_MAPPING[$problemChildId] ?? '';
        } else {
            $problemChildIdText = OrderEnum::PROBLEM_PID_2_CHILDREN_MAPPING[$problemChildId] ?? '';
        }
        $typeText           = $problemPidText . '-' . $problemChildIdText;

        $jumpUrl = \App\Service\OpenShop\Feishu\BaseService::getWorkOrderDetailUrl($workOrderNo);

        if ($problemPid == OrderEnum::PROBLEM_PID_1) {// 仓储配送问题

            $arrivalNoteImg     = $params['arrivalNoteImg'] ?? [];    // 到货单照片
            $productAbnormalImg = $params['productAbnormalImg'] ?? [];// 产品异常处照片
            $resourcesList      = self::uploadFsImage($workOrderNo, array_merge($arrivalNoteImg, $productAbnormalImg));

            $templateData = [
                'workOrderNo'        => $workOrderNo,                        // 工单号
                'createTime'         => date('Y-m-d H:i:s', $createTime),    // 创建时间
                'shopName'           => $shopName,                           // 门店名称
                'typeText'           => $typeText,                           // 工单类型
                'bookTime'           => $params['bookTime'] ?? '-',          // 订货时间
                'deliverArrivalTime' => $params['deliverArrivalTime'] ?? '-',// 物流到达时间
                'problemDesc'        => $params['problemDesc'] ?? '-',       // 问题描述
                'shareImgList'       => $resourcesList ? array_chunk($resourcesList, 3) : [],
                'buttonText'         => '点击查看',
                'jumpUrl'            => $jumpUrl,
                'color'              => 'blue',
                'title'              => $shopCode . '有新的' . $typeText . '反馈，请注意',
            ];

            $templateJson = view()->file(
                app_path('Remote/Feishu/FsTemplate/WorkOrder/AddWorkOrderCpFsTemplate.blade.php'), $templateData,
            )->render();

            // 新增仓储配送问题飞书群通知
            BuildFs::newRobot(SendFs::ROBOT_ADD_WORK_ORDER_CP_1, BuildFs::MSG_TYPE_CARD)
                ->setCardContent(json_decode($templateJson, true))
                ->send();
            return;
        }

        if ($problemPid == OrderEnum::PROBLEM_PID_2) {// 品质异常问题

            // 选择问题产品
            $errJdeCodes    = $params['errJdeCodes'] ?? [];
            $goodsName      = array_column($errJdeCodes, 'goods_name');
            $errProductName = implode(',', $goodsName);

            $chooseFactory = [];
            foreach ($errJdeCodes as $errGoods) {
                $chooseFactory[] = $errGoods['supplier_id'] ?? 0;
            }
            $factoryName = '';
            if ($chooseFactory) {
                $factory     = ProblemFeedbackService::getOrmSupplier(); //查询所有厂家信息
                $factory     = array_column($factory, 'text', 'value');
                $tempFactory = [];
                foreach ($chooseFactory as $chooseFactoryValue) {
                    $tempFactory[] = $factory[$chooseFactoryValue] ?? '其他';//供应商名称
                }
                $factoryName = implode(',', array_unique($tempFactory));
            }

            $resourcesList = self::uploadFsImage($workOrderNo, $params['productAbnormalImg'] ?? []);

            $templateData = [
                'workOrderNo'     => $workOrderNo,                                          // 工单号
                'createTime'      => date('Y-m-d H:i:s', $createTime),                      // 创建时间
                'shopName'        => $shopName,                                             // 门店名称
                'typeText'        => $typeText,                                             // 工单类型
                'errProductName'  => $errProductName,                                       // 选择问题产品
                'manufactureTime' => $params['manufactureTime'] ?? '-',                     // 产品内袋生产日期
                'problemDesc'     => $params['problemDesc'] ?? '-',                         // 问题描述
                'chooseFactory'   => $factoryName,                                          // 生产厂家
                'shareImgList'    => $resourcesList ? array_chunk($resourcesList, 3) : [],
                'buttonText'      => '点击查看',
                'jumpUrl'         => $jumpUrl,
                'color'           => 'blue',
                'title'           => $shopCode . '有新的' . $typeText . '反馈，请注意',
            ];

            $templateJson = view()->file(
                app_path('Remote/Feishu/FsTemplate/WorkOrder/AddWorkOrderFsTemplate.blade.php'), $templateData,
            )->render();

            // 新增品质工单飞书群通知-供应商品控群
            BuildFs::newRobot(SendFs::ROBOT_ADD_WORK_ORDER_PK_1, BuildFs::MSG_TYPE_CARD)
                ->setCardContent(json_decode($templateJson, true))
                ->send();

            // 新增品质工单飞书群通知-PDCA 品控群
            BuildFs::newRobot(SendFs::ROBOT_ADD_WORK_ORDER_PK_2, BuildFs::MSG_TYPE_CARD)
                ->setCardContent(json_decode($templateJson, true))
                ->send();
            return;
        }
    }

    /**
     * 图片上传至飞书 用于卡片通知
     * @param string $workOrderNo
     * @param array $img
     * @return array
     */
    public static function uploadFsImage(string $workOrderNo, array $img): array
    {
        $resourcesList = [];
        if (!$img) {
            return $resourcesList;
        }
        $saveDir       = getTmpDir('/workOrder/addWorkOrder/' . formatDateYmd(time()));
        $fileSystem    = getFileSystem();
        if (!$fileSystem->isDirectory($saveDir)) {
            $fileSystem->makeDirectory($saveDir, 0777, true);
        }

        foreach ($img as $v) {
            $file = $v . '?x-oss-process=image/resize,m_fill,h_2000,w_2000';

            $filePath = vsprintf('%s/%s.%s', [$saveDir, md5($file), (new \SplFileInfo($file))->getExtension()]);
            $fileSystem->put($filePath, file_get_contents($file));

            try {
                $fsImgKey = FeishuImageRemote::uploadImage($filePath)['image_key'];//图片上传至飞书
            } catch (\Exception $exception) {
                logInfo(
                    '品质工单新增工单图片上传至飞书报错', collect(
                    [
                        'file'        => $file,
                        'workOrderNo' => $workOrderNo,
                        'msg'         => $exception->getMessage(),
                    ],
                ), true, true,
                );
                $fsImgKey = '';
            }
            if ($fsImgKey) {
                $resourcesList[] = [
                    'file'     => $file,
                    'fsImgKey' => $fsImgKey,
                ];
            }
        }
        return $resourcesList;
    }
}
